package hzn.util;

import hzn.dao.UserDao;
import hzn.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyRealm extends AuthorizingRealm{
    @Autowired
    UserDao dao;

    @Override
    public String getName() {
        return "myrealm";
    }

    //用户授权处理，判断用户是否拥有某个角色或权限时，会调用到这个方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {
        String username=(String)p.getPrimaryPrincipal();
        String role=dao.selectRoleByName(username);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRole(role);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken t) throws AuthenticationException {
        String name= (String) t.getPrincipal();
        String pass=new String((char[])t.getCredentials());
        User u= dao.selectUser(name);
        if(u==null){
            throw  new AuthenticationException("用户名不正确");
        }
        //用户名正确
        String dbPass=u.getPass();
        String salt=u.getSalt();
        //把用户输入的密码添加盐值加密
        String tmp=PassUtil.encode(pass,salt);
        //判断跟数据库中保存的密文是否相同
        if(!tmp.equals(dbPass)){
            throw  new AuthenticationException("密码不正确");
        }
        return new SimpleAuthenticationInfo(name,pass,getName());
    }
}
